package sc.common.test.protostuff.impl;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

import sc.common.test.protostuff.DeSerializer;

import com.dyuproject.protostuff.JsonIOUtil;
import com.dyuproject.protostuff.Schema;

public class JsonDeSerializer implements DeSerializer{

    @Override
    public <T> String serialize(T object, Schema<T> objectSchema) {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try {
            JsonIOUtil.writeTo(bos, object, objectSchema, false);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bos.toString();
    }

    @SuppressWarnings("unchecked")
    @Override
    public <T> T deserialize(String serial, Schema<T> objectSchema) {
        T deserial = null;
        try {
            deserial = (T) objectSchema.typeClass().newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        try {
            JsonIOUtil.mergeFrom(serial.getBytes(), deserial, objectSchema, false);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return deserial;
    }

}
